#include"../include/lib_headers.h"
char* list_dir(char *directory_path, int flag, char *text_file_path) {
	char to_write[LARGESIZE]="", str[LARGESIZE]="";
	node *temp, *child;

	/* VFS not mounted */
	if ( h == NULL || l1 == NULL) {
		sprintf(output_message,"%s %s","listdir_FAILURE",ERR_VFS_LISTDIR_03);	
		return output_message;
	}
	
	/* Insufficient Arguments */
	if(strlen(directory_path) == 0 || strlen(text_file_path) == 0 ){
		sprintf(output_message,"%s %s","listdir_FAILURE",ERR_VFS_LISTDIR_00);	
		return output_message;
	}
	
	/* Invalid Flag */
	if(flag!=0 && flag!=1){
		sprintf(output_message,"%s %s","listdir_FAILURE",ERR_VFS_LISTDIR_02);	
		return output_message;
	}
	
	/* Cannot create Output file */
	FILE *fp=fopen(text_file_path, "a");	
	if(fp==NULL){
		sprintf(output_message,"%s %s","listdir_FAILURE",ERR_VFS_LISTDIR_04);	
		return output_message;
	}
	fseek(fp, 0, SEEK_END);
	
	/* Can't find specified path or Directory */
	if(find_node(l1->next, directory_path) == NULL || directory_path[0] != '/' ){
		sprintf(output_message,"%s %s","listdir_FAILURE",ERR_VFS_LISTDIR_01);	
		return output_message;
	}
	
	/* Cannot list the contents of a file by this function */
	if(strcmp(directory_path, "/") != 0 && strcmp(find_node(l1->next,directory_path)->fd_pointer->fileType, "dir") != 0){
		sprintf(output_message,"%s %s","listdir_FAILURE",ERR_VFS_LISTDIR_01);	
		return output_message;
	}
	
	temp=find_node(l1->next, directory_path);

	if(strcmp(directory_path, "/") == 0)
		child=temp;
	else	
		child = temp->child;

	
	if(flag == 0){
		if(child == NULL){
		}
		else {
			while(child!=NULL){
				sprintf(str, "FileName = %s\tFullPath =  %s\tFileType =  %s\tBlock No = %d \n",
					child->fd_pointer->fileName, child->fd_pointer->fullPath,
					child->fd_pointer->fileType, child->fd_pointer->blockno);
				strcat(to_write, str);
				child = child->sibling;
			}
			strcat(to_write, "\n");
		}		
	}
	
	else if(flag == 1){
		if(child == NULL){
		}
		else {	
			list_traversal(child, to_write);			
		}
		strcat(to_write, "\n");
	}
	
	fwrite(to_write, strlen(to_write), 1, fp);
	sprintf(output_message,"%s","listdir_SUCCESS");	
	return output_message;	
	fclose(fp);
}


